package com.itheima.service.db.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.domain.db.AnalysisByDay;
import com.itheima.domain.db.Log;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.vo.AnalysisSummaryVo;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.mapper.AnalysisByDayMapper;
import com.itheima.mapper.LogMapper;
import com.itheima.mapper.UserInfoMapper;
import com.itheima.service.db.AnalysisByDayService;
import com.itheima.util.ComputeUtil;
import jdk.nashorn.internal.ir.LiteralNode;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

import static org.apache.dubbo.common.utils.DubboAppender.logList;


@Service
public class AnalysisByDayServiceImpl implements AnalysisByDayService {

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 保存或者修改日志分析信息
     */
    @Override
    public void saveOrUpdate() {
        //获取今日日期
        String today = DateUtil.today();
        //获取昨日一日期
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        //查询数据库中是否有今日日志信息
        QueryWrapper<AnalysisByDay> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_date", today);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(queryWrapper);
        //查询今日新增用户
        Integer numRegistered = logMapper.findByType("0102", today);
        //查询今日登陆次数
        Integer numLogin = logMapper.findByType("0101", today);
        //查询今日活跃人数
        Integer activeNum = logMapper.findActiveNum(today);
        //查询今日留存人数
        Integer numRetention1d = logMapper.selectNumRetention1d(today, yesterday);
        if (analysisByDay == null) {
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(new Date());
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumActive(activeNum);
            analysisByDay.setNumRetention1d(numRetention1d);
            //保存日志记录
            analysisByDayMapper.insert(analysisByDay);
        } else {
            analysisByDay.setRecordDate(new Date());
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumActive(activeNum);
            analysisByDay.setNumRetention1d(numRetention1d);
            analysisByDayMapper.updateById(analysisByDay);
        }
    }

    /**
     * 首页显示数据统计
     *
     * @return
     */
    @Override
    public AnalysisSummaryVo summary() {
        System.out.println("统计数据");
        //构建返回对象
        AnalysisSummaryVo summaryVo = new AnalysisSummaryVo();
        //获取今日日期
        String today = DateUtil.today();
        //获取昨日日期
        String yesterday = DateUtil.offsetDay(new Date(), -1).toString("yyyy-MM-dd");
        //查询今日日志数据
        QueryWrapper<AnalysisByDay> wrapper = new QueryWrapper<>();
        wrapper.eq("record_date", today);
        //今日日志数据
        AnalysisByDay todaySummary = analysisByDayMapper.selectOne(wrapper);
        //查询昨日日志数据
        QueryWrapper<AnalysisByDay> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("record_date", yesterday);
        AnalysisByDay yesterdaySummary = analysisByDayMapper.selectOne(wrapper1);
        //查询过去一周活跃人数
        String beginDate = DateUtil.offsetDay(new Date(), -7).toString("yyyy-MM-dd");
        long weekCount = analysisByDayMapper.selectActiveByTime(beginDate, today);
        //查询获取一月活跃人数
        beginDate = DateUtil.offsetDay(new Date(), -30).toString("yyyy-MM-dd");
        long monthCount = analysisByDayMapper.selectActiveByTime(beginDate, today);
        //赋值
        if (todaySummary == null) {
            todaySummary = new AnalysisByDay();
        }
        summaryVo.setActiveUsersToday(todaySummary.getNumActive().longValue());
        summaryVo.setLoginTimesToday(todaySummary.getNumLogin().longValue());
        summaryVo.setNewUsersToday(todaySummary.getNumRegistered().longValue());
        summaryVo.setActivePassMonth(monthCount);
        summaryVo.setActivePassWeek(weekCount);
        long cumulativeUsers = analysisByDayMapper.cumulativeUsers();
        summaryVo.setCumulativeUsers(cumulativeUsers);
        if (yesterdaySummary == null) {
            yesterdaySummary = new AnalysisByDay();
        }
        summaryVo.setActiveUsersTodayRate(ComputeUtil.computeRate(todaySummary.getNumActive(), yesterdaySummary.getNumActive()));
        summaryVo.setLoginTimesTodayRate(ComputeUtil.computeRate(todaySummary.getNumLogin(), yesterdaySummary.getNumLogin()));
        summaryVo.setNewUsersTodayRate(ComputeUtil.computeRate(todaySummary.getNumRegistered(), yesterdaySummary.getNumRegistered()));

        System.out.println("=>>>>>>>>>>>>>>" + summaryVo);
        return summaryVo;
    }

    /**
     * 在首页中，根据时间显示图标数据: 新用户 活跃用户  次日留存。这些数据是需要基于用户的操作来进行统计
     */
    @Override
    public List findDashboard(String sd, String ed, String type) {
        //数据集合
        ArrayList<Map> YearList = new ArrayList<>();
        //今年和去年的集合
        Integer YearAmount = 0;
        for (int i = 0; ; i++) {
            //新增用户
            if (StrUtil.equals("101", type)) {
                YearAmount = analysisByDayMapper.selectRegisterByTime(sd);
            }

            //102 活跃用户
            if (StrUtil.equals("102", type)) {
                YearAmount = analysisByDayMapper.selectActiveNumByTime(sd);
            }
            //103 次日留存率
            if (StrUtil.equals("103", type)) {
                YearAmount = analysisByDayMapper.selectretentionByTime(sd);
            }
            if (YearAmount == null) {
                YearAmount = 0;
            }
            HashMap hashMap = new HashMap<>();
            hashMap.put("title", sd);
            hashMap.put("amount", YearAmount);
            YearList.add(hashMap);
            sd = DateUtil.offsetDay(DateUtil.parseDate(sd).toJdkDate(), 1).toString("yyyy-MM-dd");
            //如果开始日期和结束日期相同，结束循环
            if (StrUtil.equals(sd, ed)) {
                break;
            }
        }
        return YearList;
    }
    /**
     * 根据昵称查找用户活动
     */
    @Override
    public PageBeanVo findUserInfoByuserName(Integer page, Integer pageSize, String userName) {
        IPage iPage = new Page<>(page, pageSize);
        //单个查询昵称
       // iPage = userInfoMapper.findByName(iPage, "%" + userName + "%");
        PageBeanVo pageBeanVo = new PageBeanVo(page, pageSize, iPage.getTotal(), iPage.getRecords());
        return pageBeanVo;
    }

    /**
     * 根据时间查找用户活动
     */
    @Override
    public PageBeanVo findUserInfoByDate(Integer page, Integer pageSize, String date,String nickName) {
        IPage iPage = new Page<>(page, pageSize);
        PageBeanVo pageBeanVo = new PageBeanVo();
 /*       //单查询日期
        if (date!=null&&nickName==null){
            iPage = logMapper.findByDate(iPage, date + "%");
          pageBeanVo = new PageBeanVo(page, pageSize, iPage.getTotal(), iPage.getRecords());
        }
        //单查询昵称
        if (date==null&&nickName!=null){
            //查找和当前用户昵称相似的用户
            List<Long> idList = userInfoMapper.findByName("%" + nickName + "%");
            QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("user_id", idList);
            iPage = logMapper.selectPage(iPage, queryWrapper);
            pageBeanVo = new PageBeanVo(page, pageSize, iPage.getTotal(), iPage.getRecords());
        }
        //多表查询
        if (date!=null&&nickName!=null){
            List<Long> idList = userInfoMapper.findByName("%" + nickName + "%");
            QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("user_id", idList).like("updated",date );
            iPage = logMapper.selectPage(iPage, queryWrapper);
            pageBeanVo = new PageBeanVo(page, pageSize, iPage.getTotal(), iPage.getRecords());
        }*/
        //整合版
        QueryWrapper<UserInfo> queryWrapperName = new QueryWrapper<>();
        if (nickName!=null){
            queryWrapperName.like("nickname",nickName);
        }
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapperName);
        ArrayList<Long> idList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            idList.add(userInfo.getId());
        }
        QueryWrapper<Log> queryWrapperDate = new QueryWrapper<>();
        if (date!=null){
            queryWrapperDate.in("user_id", idList).like("updated",date );
        }else{
            queryWrapperDate.in("user_id", idList);
        }
        iPage = logMapper.selectPage(iPage, queryWrapperDate);
        pageBeanVo = new PageBeanVo(page, pageSize, iPage.getTotal(), iPage.getRecords());
        return pageBeanVo;
    }
}